//
//  ZZComposeView.swift
//  sina
//
//  Created by 张鹏 on 16/5/29.
//  Copyright © 2016年 ZP. All rights reserved.
//

import UIKit

class ZZComposeView: UIView {
    
    //用数组保存按钮
    private lazy var btns : [ZZComposeButton] = [ZZComposeButton]()

    //保存参数, 方便其他地方使用
    weak var target: UIViewController?
    
    func show(targetVC target: UIViewController) {
        self.target = target
        //添加视图
        target.view.addSubview(self)
    }

    override init(frame: CGRect) {
        //设置frame
        let rect = UIScreen.mainScreen().bounds
        
        super.init(frame: rect)

      setUpUI()
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setUpUI() {
    
    backgroundColor = UIColor.whiteColor()
        
        //添加图片
        addSubview(backImageView)
    
        addSubview(sloganImageView)
        
        sloganImageView.snp_makeConstraints { (make) in
            
            make.centerX.equalTo(self.snp_centerX)
            make.top.equalTo(self.snp_top).offset(100)
            
        }
        
        //添加按钮
        addChildButtons()

    }
    
 
    
    
    private func addChildButtons() {
        //字典转模型
        //九宫格模式
        let count = composeViewItems.count
//        let count = 6
        print(count)
        //设置按钮高和宽
        let w : CGFloat = 90
        let h : CGFloat = 90
        let margin : CGFloat = (screenWidth - w * 3) / 4
        
        for i in 0..<count {
    
            let btn = ZZComposeButton()
            //给按钮赋值
            let item = composeViewItems[i]
            //composeItem : button模型赋值
            btn.composeItem = item
         
            //设置frame
            let row = i / 3
            let col = i % 3
            let x = margin + CGFloat(col) * (margin + w)
            let y = screenHeight + CGFloat(row) * (margin + h)
            
            btn.frame = CGRect(x: x, y: y, width: w, height: h)
            print(btn.frame)
            
            //按钮的点击事件
            //因为按钮实在view上的,所以用ZZComposeView , 不用ZZComposeButton
            btn.addTarget(self, action: #selector(ZZComposeView.addBtnDidClick(_:)), forControlEvents: .TouchUpInside)
            
            //把btn添加到视图中
            self.addSubview(btn)
            //添加到数组中
            btns.append(btn)
        }
    }
    
    //按钮的点击事件
    @objc func addBtnDidClick(btn : ZZComposeButton) {
    
        for button in btns {
        
            var scale : CGFloat = 0
            //判断是否是点击按钮
            if button == btn {
            //放大
            scale = 2.0
            }else {
            //缩小
            scale = 0.2
            }
        //动画效果
        UIView.animateWithDuration(0.25, animations: {
                //改变btn
            btn.alpha = 0
            btn.transform = CGAffineTransformMakeScale(scale, scale)
                
            }, completion: { (_) in
                    print("OK")
        })
    }

        //跳转控制器
      print(btn.composeItem)
        guard let target = btn.composeItem?.target else {
            return
        }
        
        //就是根据字符串来获取控制器对应类型
        let type = NSClassFromString(target) as! UIViewController.Type
        //初始化控制器
        let vc = type.init()
        let nav = UINavigationController(rootViewController: vc)
        //页面跳转  视图不能跳转页面
        self.target?.presentViewController(nav, animated: true, completion: {
            self.removeFromSuperview()
        })
        
    }
    
    

    //点击屏幕移除按钮
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        
        for (index,btn) in btns.reverse().enumerate() {
            startAnimation(btn, index: index,offset: 350)
        }
    }
    
    //将要移动到父视图
    //系统方法
    override func willMoveToSuperview(newSuperview: UIView?) {
        
        super.willMoveToSuperview(superview)
        
        for (index,btn) in btns.enumerate() {
            startAnimation(btn, index: index,offset: -150)
            
            print("......\(btn.frame)")
        }
        
    }

    
    private func startAnimation(btn: ZZComposeButton, index: Int, offset: CGFloat) {
        UIView.animateWithDuration(0.75, delay: Double(index) * 0.2, usingSpringWithDamping: 0.6, initialSpringVelocity: 5, options: [], animations: {
            //修改按钮的y值
            btn.center = CGPoint(x: btn.center.x, y: btn.center.y + offset)
            }, completion: { (_) in
                if offset > 0 {
                    //移除
                    self.removeFromSuperview()
                }
        })
    }
    
    
    
    //懒加载控件
    //TODO: 高斯模糊的模式....
    private lazy var backImageView : UIImageView = UIImageView(image: UIImage.snapShotCurrentWindow().applyLightEffect())
 
    private lazy var composeViewItems : [ZZCompostViewItem] = {
    
        var array = [ZZCompostViewItem]()
        
        //获取文件数据
        //获取文件路径
        let path = NSBundle.mainBundle().pathForResource("Compose.plist", ofType: nil, inDirectory: nil)
    
        //获取数组
        let itemArray = NSArray(contentsOfFile: path!) as! [[String : AnyObject]]
        
        //遍历数组
        for item in itemArray {
            let composeItem = ZZCompostViewItem(dict: item)
            array.append(composeItem)
        }

        return array
    }()
    
    private lazy var sloganImageView : UIImageView = UIImageView(image: UIImage(named: "compose_slogan"))

}
